package com.ross.shiro;

import com.ross.pojo.User;
import com.ross.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author RossZhang
 */
public class UserRealm extends AuthorizingRealm {
    public UserService getUserService() {
        return userService;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    private UserService userService;

    /**
     * 授权（w为当前登录的用户授予权限角色）
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 验证（为当前登录的用户进行身份验证）
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //从authenticationToken获取当前用户信息
        String username = (String) authenticationToken.getPrincipal();
        try {
            //根据用户名得到用户信息
            User user = userService.findUserByName(username);
            if (user != null){
                //验证用户名于密码
                AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),"XXX");
                //返回验证信息

                return authenticationInfo;

            }

        }catch (Exception e){
            e.printStackTrace();
        }
        //验证失败
        return null;
    }
}
